package controller.manufacture;

import java.sql.SQLException;

import service.CoffeeService;
import to.JobTO;
import util.CoffeeUtil;

public class Grinder extends Thread {
	private static CoffeeService service;

	public Grinder(CoffeeService service) {
		this.service = service;
	}

	@Override
	public void run() {
		while (true) {
			int job;
			try {
				job = service.selectMachineWaitingJob("글라인더");
				while (job > 0) {
					try {
						// 글라인더 상태 변환 - 작업중
						// 대기중 작업 업데이트 - 0으로 만들어줌
						// 배전두Silo에서 원두량 - 100kg
						service.updateMachineStatus("글라인더", "작업중");
						service.updateMachineWaitingJob("글라인더", -1);
						String sTime = CoffeeUtil.getNow();
						CoffeeUtil.sleep(2000);
						service.updateSiloStatus("배전두silo", -100);
						String eTime = CoffeeUtil.getNow();
						// 배전두보통원두출고 등록
						JobTO jto = new JobTO("배전두보통원두출고", sTime, eTime);
						jto.setWorkLoad(-100);
						service.insertJobInfo(jto);

						String startTime = CoffeeUtil.getNow();
						CoffeeUtil.sleep(CoffeeUtil.GRINDING_TIME);// 1분 글라인딩
						String endTime = CoffeeUtil.getNow();
						// 글라인딩 작업 등록
						JobTO jto2 = new JobTO("글라인딩", startTime, endTime);
						jto2.setWorkLoad(0);
						service.insertJobInfo(jto2);
						// 프레셔 대기중작업 1 늘려준다.
						// 글라인더 상태 변환 - 대기중
						service.updateMachineWaitingJob("프레셔", 1);
						clean();
						service.updateMachineStatus("글라인더", "대기중");
						job = service.selectMachineWaitingJob("글라인더");
					} catch (SQLException e) {
						e.printStackTrace();

					}
				}
			} catch (SQLException e1) {
				e1.printStackTrace();
			}
		}
	}

	static public void clean() {
		try {
			String startTime = CoffeeUtil.getNow();
			service.updateMachineStatus("글라인더", "청소중");
			CoffeeUtil.sleep(CoffeeUtil.GRINDER_CLEAN_TIME);
			String endTime = CoffeeUtil.getNow();
			JobTO jto = new JobTO("글라인더 청소", startTime, endTime);
			// 쿨러 상태 변경 - 대기중
			service.insertJobInfo(jto);
			service.updateMachineStatus("글라인더", "대기중");
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}
}
